package com.example.app.Websocket;
import android.annotation.SuppressLint;
import android.util.Log;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.IceCandidate;
import org.webrtc.SessionDescription;
import java.net.URI;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class WebSocketManager {
    private static final String TAG = "WebSocketManager";
    private WebSocketClient webSocket;
    private final String serverUrl;
    private final String username;
    private OnWebSocketMessageListener messageListener;
    public interface OnWebSocketMessageListener {
        void onMessageReceived(JSONObject message);
        void onConnectionOpen();
        void onConnectionClosed();
    }
    public WebSocketManager(String serverUrl, String username) {
        this.serverUrl = serverUrl;
        this.username = username;
    }
    public void setMessageListener(OnWebSocketMessageListener listener) {
        this.messageListener = listener;
    }
    public void connect() {
        try {
            SSLContext sslContext = createInsecureSSLContext();
            URI uri = new URI(serverUrl + "?username=" + username);
            webSocket = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.d(TAG, "WebSocket connected");
                    if (messageListener != null) {
                        messageListener.onConnectionOpen();
                    }
                }
                @Override
                public void onMessage(String message) {
                    try {
                        JSONObject json = new JSONObject(message);
                        if (messageListener != null) {
                            messageListener.onMessageReceived(json);
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "JSON parse error: " + e.getMessage());
                    }
                }
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    Log.d(TAG, "WebSocket closed");
                    if (messageListener != null) {
                        messageListener.onConnectionClosed();
                    }
                }
                @Override
                public void onError(Exception ex) {
                    Log.e(TAG, "WebSocket error: " + ex.getMessage());
                }
            };
            webSocket.setSocketFactory(sslContext.getSocketFactory());
            webSocket.connect();
        } catch (Exception e) {
            Log.e(TAG, "WebSocket connection error: " + e.getMessage());
        }
    }
    public void sendJsonMessage(String type, String toUser, Object data) {
        try {
            JSONObject message = new JSONObject();
            message.put("type", type);
            message.put("fromUser", username);
            message.put("toUser", toUser);
            if (data != null) {
                if (data instanceof SessionDescription) {
                    SessionDescription sdp = (SessionDescription) data;
                    message.put("sdp", sdp.description);
                    message.put("type", sdp.type.canonicalForm());
                } else if (data instanceof IceCandidate) {
                    IceCandidate candidate = (IceCandidate) data;
                    message.put("sdpMid", candidate.sdpMid != null ? candidate.sdpMid : "");
                    message.put("sdpMLineIndex", candidate.sdpMLineIndex);
                    message.put("candidate", candidate.sdp);
                } else if (data instanceof String) {
                    message.put("msg", data);
                }
            }
            if (webSocket != null && webSocket.isOpen()) {
                webSocket.send(message.toString());
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSON error: " + e.getMessage());
        }
    }

    public void disconnect() {
        if (webSocket != null) {
            webSocket.close();
        }
    }
    private SSLContext createInsecureSSLContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            @SuppressLint("TrustAllX509TrustManager")
            public void checkClientTrusted(X509Certificate[] certs, String authType) {}
            @SuppressLint("TrustAllX509TrustManager")
            public void checkServerTrusted(X509Certificate[] certs, String authType) {}
        }};
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        return sslContext;
    }
}